import { useRefs } from "/@/core";
import { deepTree } from "/@/core/utils";
import { ElMessage, ElMessageBox, ElLoading } from "element-plus";
import { defineComponent, h, inject, ref } from "vue";

export default defineComponent({
	name: "gdshop-category-move",
	props: {
		categoryTypeId: {
			type: [Number, String]
		},
		categoryTypeStr: {
			type: String
		},
		moveFnOne: {
			type: String
		},
		moveFnTwo: {
			type: String
		}
	},
	emits: ["success", "error"],

	setup(props: any, { emit }) {
		const service = inject<any>("service");
		const { refs, setRefs }: any = useRefs();

		// 树形列表
		const list = ref<any[]>([]);

		// 刷新列表
		async function refresh() {
			await service.cms.category.list({ type: props.categoryTypeId,type_str: props.categoryTypeStr }).then((res: any[]) => {
				list.value = deepTree(res, "parent_id");
			});
			return list;
		}

		// 转移
		async function toMove(ids: any[]) {
			let loading = null;
			const loadingIndex = setTimeout(function () {
				// 超过 500 毫秒，显示加载
				loading = ElLoading.service({
					lock: true
				});
			}, 500);
			await refresh();
			// 清除掉 setTimeout
			clearTimeout(loadingIndex);
			if (loading != null) {
				// @ts-ignore
				loading.close();
			}

			refs.value.form.open({
				props: {
					title: "分类转移",
					width: "600px",
					labelWidth: "80px"
				},
				items: [
					{
						label: "选择分类",
						prop: "category",
						component: {
							name: "slot-move"
						}
					}
				],
				on: {
					submit: (data: any, { done, close }: any) => {
						console.log(data);
						if (!data.category) {
							ElMessage.warning("请选择分类");
							return done();
						}

						const { cat_name, id } = data.category;

						ElMessageBox.confirm(`是否转移到分类 ${cat_name} 下`, "提示", {
							type: "warning"
						})
							.then(() => {
								service[props.moveFnOne][props.moveFnTwo]
									["move"]({
										category_id: id,
										ids: ids
									})
									.then((res: any) => {
										close();
										emit("success", res);
									})
									.catch((err: any) => {
										done();
										emit("error", err);
									});
							})
							.catch(() => null);
					}
				}
			});
		}

		return {
			refs,
			list,
			setRefs,
			refresh,
			toMove
		};
	},

	render(ctx: any) {
		return (
			<div class="cl-dept-move">
				{h(
					<cl-form ref={ctx.setRefs("form")}></cl-form>,
					{},
					{
						"slot-move"({ scope }: any) {
							return (
								<div
									style={{
										border: "1px solid #eee",
										borderRadius: "3px",
										padding: "2px"
									}}>
									<el-tree
										data={ctx.list}
										props={{
											label: "cat_name"
										}}
										node-key="id"
										highlight-current
										onNodeClick={(e: any) => {
											scope["category"] = e;
										}}></el-tree>
								</div>
							);
						}
					}
				)}
			</div>
		);
	}
});
